__version__ = "$Revision: 120 $"
__date__ = "$Date: 2011-07-31 16:47:57 +0200 (So, 31 Jul 2011) $"
__lastChangedBy__ = "$Author: wolters@3sconsult.de $"
__repository__ = "$HeadURL: https://sir3spy.googlecode.com/svn/Sir3sPy/Utils/trunk/DbOraUtest.py $"

"""Class DbOra's UnitTest.

Description
-----------
    - Class(es): test_DbOra.
    - Infile unit test of the class.
"""

import os
import sys
import logging
import unittest
import re

from Db import DbOra

testDbOraName='DbOraUtest'
testDbOraUser='DbOraUtest'
testDbOraPassword='sir3s'
testDbOraServer='xe'
testDbOraConnectionsString='DbOraUtest/sir3s@xe'

testDbOraConnectionsStringAdmin='system/sir3s@xe'
                      
class test_DbOra(unittest.TestCase):
    """
    Tries to Create and Delete Databases.
    Ensure, that testDbOraConnectionsStringAdmin has correct value. 
    """
 
    def setUp(self):
        """
        """      

        fileName =__file__
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'.setUp'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)    
        
        logger.debug('Start.')          

        self.db = DbOra(testDbOraConnectionsString)
        if not self.db.isConnectionOk():
            self.db.createDatabase(testDbOraConnectionsStringAdmin)

        if not self.db.isConnectionOk():
            logger.error('Creation of {:s} was not successful.'.format(testDbOraConnectionsString))
            
        self._DbOraUtestTestTableCeate()
        
        logger.debug('_Done.')   

    def _DbOraUtestTestTableCeate(self):
        """
        """   
        sqlCmd='CREATE TABLE DbOraUtestTable (TestCol1 int NULL, TestCol2 int NULL)'
        self.db.executeCommand(sqlCmd)

        sqlCmd='INSERT INTO DbOraUtestTable VALUES (11,12)'
        self.db.executeCommand(sqlCmd)        

        sqlCmd='INSERT INTO DbOraUtestTable VALUES (21,22)'
        self.db.executeCommand(sqlCmd) 
 
        self.sqlTestCommand='select * from DbOraUtestTable'

    def _DbOraUtestResultChecksqlTestCommand(self,colNames,data):
        """
        """           
        self.assertEqual(colNames[0],'TESTCOL1')  
        self.assertEqual(data[0][0],11)  
        self.assertEqual(data[1][0],21)  
        self.assertTupleEqual(data[0],(11, 12))  
                
    def tearDown(self):
        """
        """        

        fileName =__file__
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'.tearDown'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)    
        
        logger.debug('Start.')         
        
        if self.db.isConnectionOk():
            self.db.deleteDatabase(testDbOraConnectionsStringAdmin)

        if self.db.isConnectionOk():
            logger.error('Deletion of {:s} was not successful.'.format(testDbOraConnectionsString))

        logger.debug('_Done.')   

    def test_executeSelect(self):
        """        
        """           
 
        colNames,data=self.db.executeSelect(self.sqlTestCommand)
        self._DbOraUtestResultChecksqlTestCommand(colNames,data) 
       
        colNames,data=self.db.executeSelect(self.sqlTestCommand+'x')
        self.assertEqual(colNames,None)
        self.assertEqual(data,None)

    def test_executeSelectScript(self):
        """        
        """     
        f = open("tmp.sql",'w')        
        f.write(self.sqlTestCommand)
        f.close()
            
        colNames,data=self.db.executeSelectScript("tmp.sql")
        os.remove("tmp.sql")  
        self._DbOraUtestResultChecksqlTestCommand(colNames,data)   
        
        f = open("tmp.sql",'w')        
        f.write(self.sqlTestCommand+'x')
        f.close()
            
        colNames,data=self.db.executeSelectScript("tmp.sql")
        os.remove("tmp.sql")   
        self.assertEqual(colNames,None)
        self.assertEqual(data,None)                 
     
"""Infile unit test of the module."""                     
if __name__ == "__main__":

    # logging configuration
    filename=__file__
    loggerName=filename[__file__.find('Sir3sPy'):].replace('.py','').replace('\\','.').replace('/','.')
    logging.getLogger(loggerName).addHandler(logging.NullHandler())
    # configure logfile
    moduleName,ext=os.path.splitext(os.path.basename(__file__))     
    logFileName = os.path.join(os.getcwd(),moduleName+'.log') 
    # configure logging       
    logging.basicConfig(filename=logFileName,filemode='w',level=logging.DEBUG,format="%(asctime)s ; %(name)-60s ; %(levelname)-7s ; %(message)s")        

    try:    
        logger = logging.getLogger(loggerName)
        
        #test
        testClassNamesRegEx = re.compile("test_")
        testClassNames = filter(testClassNamesRegEx.search,dir())        
        testClassNamesDotted = [moduleName+'.'+testClassName for testClassName in testClassNames]
        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(testClassNamesDotted)
        unittest.TextTestRunner(verbosity=2).run(suite)
        
        sys.exit(0) 
        
    except SystemExit:        
        pass    
    except:
        logger.error('Exception.') 
    finally:                                         
        sys.exit(0)                        
